<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['group','parentuser'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($row->group_id != $params['group_id']) {
                // 修改当前用户身份
                $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $ids]);
                if($user_relation) {
                    $user_relation->group_id = $params['group_id'];
                    $user_relation->save();
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException| \think\exception\PDOException |Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);

        // 清除绑定关系
        model('app\common\model\User')
            ->where('pid',$ids)
            ->update(['pid' => 0]);
        model('app\common\model\UserRelationModel')
            ->where('p_user_id',$ids)
            ->update(['p_user_id' => 0]);
//        $user_id_field = "user_id_{$row->group_id}";
//        model('app\common\model\UserRelationModel')
//            ->where($user_id_field,$ids)
//            ->update([$user_id_field => 0]);

        $this->success();
    }


    /**
     * 推广详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids,['group','parentuser']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if(isset($row->parentuser) && !empty($row->parentuser)){
            $row->parentuser->group = model('app\admin\model\UserGroup')->get($row->parentuser->group_id);
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $user_id = $row->id;
        $user_relation = model('app\admin\model\user\UserRelation')
            ->get(['user_id' => $user_id], ['user', 'group', 'puser', 'user1', 'user2', 'user3', 'user4',]);
        // 累计佣金/积分
        $total_brokerage = model('app\common\model\UserBrokerageLogModel')
            ->where('to_user_id',$user_id)
            ->sum('brokerage');
        // 累计推广人数
        $total_popularize_num = model('app\common\model\UserRelationModel')
            ->where('p_user_id',$user_id)
            ->count();
        // 累计推广单数
        $user_brokerage_order_ids = model('app\common\model\UserBrokerageLogModel')
            ->where('to_user_id',$user_id)
            ->column('order_id');
        $total_order_num = count(array_unique($user_brokerage_order_ids));

        $user_relation_group_field = "user_id_{$user_relation->group_id}";
        // 推广用户数
        $user_1_ids = model('app\common\model\UserRelationModel')
            ->where('group_id',1)
            ->where($user_relation_group_field,$user_id)
            ->column('user_id');
        $user_1_count = count(array_unique($user_1_ids));
        $user_1_list = model('app\common\model\User')
            ->field('id,nickname,avatar,group_id,jointime')
            ->whereIn('id',$user_1_ids)
            ->select();
        foreach ($user_1_list as $item) {
            $item->avatar = full_url($item->avatar);
            $item->jointime = date('Y-m-d',$item->jointime);
            // 累计推广人数
            $user_1_ids = model('app\common\model\UserRelationModel')
                ->where('p_user_id',$item->id)
                ->column('user_id');
            $item->total_user = count($user_1_ids);
            // 累计佣金
            $user_1_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->whereIn('to_user_id',$item->id)
                ->sum('brokerage');
            $item->total_brokerage = $user_1_total_brokerage;
            // 累计推广订单
            $user_1_total_order_ids = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$item->id)
                ->column('order_id');
            $user_1_total_order_num = count(array_unique($user_1_total_order_ids));
            $item->total_order_num = $user_1_total_order_num;
        }
        // 推广门店数
        $user_2_ids = model('app\common\model\UserRelationModel')
            ->where('group_id',2)
            ->where($user_relation_group_field,$user_id)
            ->column('user_id');
        $user_2_count = count(array_unique($user_2_ids));
        $user_2_list = model('app\common\model\User')
            ->field('id,nickname,avatar,group_id,jointime')
            ->whereIn('id',$user_2_ids)
            ->select();
        foreach ($user_2_list as $item) {
            $item->avatar = full_url($item->avatar);
            $item->jointime = date('Y-m-d',$item->jointime);
            // 累计推广人数
            $user_2_ids = model('app\common\model\UserRelationModel')
                ->where('p_user_id',$item->id)
                ->column('user_id');
            $item->total_user = count($user_2_ids);
            // 累计佣金
            $user_2_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->whereIn('to_user_id',$item->id)
                ->sum('brokerage');
            $item->total_brokerage = $user_2_total_brokerage;
            // 累计推广订单
            $user_2_total_order_ids = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$item->id)
                ->column('order_id');
            $user_2_total_order_num = count(array_unique($user_2_total_order_ids));
            $item->total_order_num = $user_2_total_order_num;
        }
        // 推广分公司数
        $user_3_ids = model('app\common\model\UserRelationModel')
            ->where('group_id',3)
            ->where($user_relation_group_field,$user_id)
            ->column('user_id');
        $user_3_count = count(array_unique($user_3_ids));
        $user_3_list = model('app\common\model\User')
            ->field('id,nickname,avatar,group_id,jointime')
            ->whereIn('id',$user_3_ids)
            ->select();
        foreach ($user_3_list as $item) {
            $item->avatar = full_url($item->avatar);
            $item->jointime = date('Y-m-d',$item->jointime);
            // 累计推广人数
            $user_3_ids = model('app\common\model\UserRelationModel')
                ->where('p_user_id',$item->id)
                ->column('user_id');
            $item->total_user = count($user_3_ids);
            // 累计佣金
            $user_3_total_brokerage = model('app\common\model\UserBrokerageLogModel')
                ->whereIn('to_user_id',$item->id)
                ->sum('brokerage');
            $item->total_brokerage = $user_3_total_brokerage;
            // 累计推广订单
            $user_3_total_order_ids = model('app\common\model\UserBrokerageLogModel')
                ->where('to_user_id',$item->id)
                ->column('order_id');
            $user_3_total_order_num = count(array_unique($user_3_total_order_ids));
            $item->total_order_num = $user_3_total_order_num;
        }

        $total_popularize_num = $user_1_count + $user_2_count + $user_3_count;

        $this->view->assign("user_relation", $user_relation);
        $this->view->assign("total_brokerage", $total_brokerage);
        $this->view->assign("total_popularize_num", $total_popularize_num);
        $this->view->assign("total_order_num", $total_order_num);
        $this->view->assign("user_1_count", $user_1_count);
        $this->view->assign("user_1_list", $user_1_list);
        $this->view->assign("user_2_count", $user_2_count);
        $this->view->assign("user_2_list", $user_2_list);
        $this->view->assign("user_3_count", $user_3_count);
        $this->view->assign("user_3_list", $user_3_list);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 设置成为门店
     */
    public function setuser2($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->group_id != 1){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $group_id = 2;
        $result = false;
        Db::startTrans();
        try {
            $params['group_id'] = $group_id;
            $result = $row->allowField(true)->save($params);
            if($result) {
                // 更改用户关系
                // 修改当前用户身份
                $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $ids]);
                if($user_relation) {
                    $user_relation->user_id_2 = 0;
                    $user_relation->group_id = $group_id;
                    $user_relation->save();
                }
                // 修改其推广用户关系链
                // 将其直推的用户关系清掉
                model('app\common\model\UserRelationModel')
                    ->whereIn('group_id',[1])
                    ->where('p_user_id',$ids)
                    ->update(['user_id_1' => 0]);
            }
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }


    /**
     * 设置成为分公司
     */
    public function setuser3($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->group_id != 2){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $group_id = 3;
        $result = false;
        Db::startTrans();
        try {
            $params['group_id'] = $group_id;
            $result = $row->allowField(true)->save($params);
            if($result) {
                // 更改用户关系
                // 修改当前用户身份
                $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $ids]);
                if($user_relation) {
                    $user_relation->user_id_3 = 0;
                    $user_relation->group_id = $group_id;
                    $user_relation->save();
                }
                // 修改其推广用户关系链
                // 升级成门店时,直推用户已经在其下面;修改直推用户的绑定关系
                model('app\common\model\UserRelationModel')
                    ->whereIn('group_id',[1])
                    ->where('p_user_id',$ids)
                    ->where('user_id_2',$ids)
                    ->update(['user_id_2' => 0,'user_id_3' => $ids]);
                // 修改间推用户绑定关系
                // 用户没有上级分公司的,归属其下面,有分公司的,直接清除
                model('app\common\model\UserRelationModel')
                    ->whereIn('group_id',[1])
                    ->where('user_id_2',$ids)
                    ->where('user_id_3',0)
                    ->update(['user_id_2' => 0,'user_id_3' => $ids]);
                model('app\common\model\UserRelationModel')
                    ->whereIn('group_id',[1])
                    ->where('user_id_2',$ids)
                    ->update(['user_id_2' => 0]);
            }
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }


    /**
     * 设置成为合伙人
     */
    public function setuser4($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->group_id != 1){
            $this->error(__('状态错误'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $result = false;
            $group_id = 4;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save(['group_id' => $group_id]);

                if($result) {
                    // 更改用户关系
                    // 修改当前用户身份
                    $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $ids]);
                    if($user_relation) {
                        $user_relation->user_id_1 = 0;
                        $user_relation->user_id_2 = 0;
                        $user_relation->user_id_3 = 0;
                        $user_relation->user_id_4 = 0;
                        $user_relation->group_id = $group_id;
                        $user_relation->save();
                    }

                    // 修改选定的分公司的绑定关系
                    model('app\common\model\UserRelationModel')
                    ->whereIn('user_id',$params['user_id_3'])
                    ->update(['user_id_4' => $ids]);

                }

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
